package com.itzhihao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzhihao.common.constant.ExistStatus;
import com.itzhihao.common.constant.StoreStatus;
import com.itzhihao.entity.Order;
import com.itzhihao.entity.Product;
import com.itzhihao.entity.Store;
import com.itzhihao.mapper.ProductMapper;
import com.itzhihao.mapper.StoreMapper;
import com.itzhihao.service.IStoreService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.CaculateDistance;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store>
    implements IStoreService {

    @Resource
    private StoreMapper storeMapper;
    @Resource
    private ProductMapper productMapper;

    @Override
    public Store getDetail(Long id) {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getId,id);
        queryWrapper.eq(Store::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        queryWrapper.eq(Store::getStatus,StoreStatus.PASS_AUDIT.ordinal());


        Store store = storeMapper.selectOne(queryWrapper);
        Map<String,Object> map = new HashMap<>();
        if(store.getUserId().equals(userId)){
            map.put("isOwn",0);
        }else{
            map.put("isOwn",1);
        }
        store.setParams(map);
        return store;
    }

    // 判断当前商店是否属于该用户
    @Override
    public Boolean hasStore(Long userId,Long storeId){
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUserId,userId)
                .eq(Store::getId,storeId);
        boolean exists = storeMapper.exists(queryWrapper);
        return exists;
    }

    /**
     * 判断自己是否有店
     * @return
     */
    @Override
    public Boolean hasOwnStore() {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUserId,userId);
       return storeMapper.exists(queryWrapper);
    }

    @Override
    public Store getOwnStoreDetail() {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUserId,userId);
        queryWrapper.eq(Store::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        return storeMapper.selectOne(queryWrapper);
    }

    @Override
    public Long getProdTotal(Long storeId) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getStoreId,storeId);
        Long total = productMapper.selectCount(queryWrapper);
        return total;
    }

    @Override
    public Store selectByUserId(Long userId) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUserId,userId);
        queryWrapper.eq(Store::getStatus,StoreStatus.PASS_AUDIT.ordinal());
        queryWrapper.eq(Store::getIsDeleted, ExistStatus.EXIST_STATUS.ordinal());
        Store store = storeMapper.selectOne(queryWrapper);
        return store;
    }

    @Override
    public Store selectByProdId(Long prodId) {
        LambdaQueryWrapper<Product> prodWrapper = new LambdaQueryWrapper<>();
        prodWrapper.eq(Product::getId,prodId);
        prodWrapper.eq(Product::getIsDeleted, ExistStatus.EXIST_STATUS.ordinal());
        Product product = productMapper.selectOne(prodWrapper);

        LambdaQueryWrapper<Store> storeWrapper = new LambdaQueryWrapper<>();
        storeWrapper.eq(Store::getId,product.getStoreId());
        storeWrapper.eq(Store::getStatus,StoreStatus.PASS_AUDIT.ordinal());
        storeWrapper.eq(Store::getIsDeleted, ExistStatus.EXIST_STATUS.ordinal());
        Store store = storeMapper.selectOne(storeWrapper);
        return store;
    }

    @Override
    public TableDataInfo getList(PageDomain pageDomain,Store store) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        Long userId = SecurityUtils.getUserId();
        TableDataInfo tableDataInfo = new TableDataInfo();
        queryWrapper
                .lambda()
                .eq(Store::getStatus,StoreStatus.PASS_AUDIT.ordinal());
        queryWrapper.lambda().ne(Store::getUserId,userId);
        Page<Store> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        queryWrapper.lambda().eq(Store::getStatus,StoreStatus.PASS_AUDIT.ordinal());
        queryWrapper.lambda().eq(Store::getIsDeleted, ExistStatus.EXIST_STATUS.ordinal());
        if(store.getSearchValue().equals("加盟上新")){
            queryWrapper.lambda().orderByDesc(Store::getUpdateTime);
            storeMapper.selectPage(page,queryWrapper);
            for (int i = 0; i < page.getRecords().size(); i++) {
                Store s = page.getRecords().get(i);
                s.setDistance(CaculateDistance.GetDistance(store.getLatitude(),store.getLongitude(),s.getLatitude(),s.getLongitude()));
            }
        }else if(store.getSearchValue().equals("距离最近") || store.getSearchValue().equals("综合")){
            storeMapper.selectPage(page,queryWrapper);
            if(store.getLongitude() == null || store.getLatitude() == null){
                return tableDataInfo;
            }
            for (int i = 0; i < page.getRecords().size(); i++) {
                Store s = page.getRecords().get(i);
                s.setDistance(CaculateDistance.GetDistance(store.getLatitude(),store.getLongitude(),s.getLatitude(),s.getLongitude()));
            }
            // 排序
            Collections.sort(page.getRecords(), new Comparator<Store>() {
                @Override
                public int compare(Store o1, Store o2) {
                    if(o1.getDistance() > o2.getDistance()){
                        return 1;
                    }else{
                        return -1;
                    }
                }
            });
//            出现其他字段 直接返回空
        }else {
            return tableDataInfo;
        }
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询到"+page.getCurrent()+"条数据");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public TableDataInfo getBackList(PageDomain pageDomain, Store store) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        if(store.getName() != null){
            queryWrapper.like(Store::getName,store.getName());
        }
        if(store.getStatus() != null){
            queryWrapper.eq(Store::getStatus,store.getStatus());
        }
        Page<Store> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        queryWrapper.eq(Store::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        queryWrapper.orderByDesc(Store::getUpdateTime);
        storeMapper.selectPage(page,queryWrapper);
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setTotal(page.getTotal());
        dataInfo.setRows(page.getRecords());
        return dataInfo;
    }

    @Override
    public boolean updateStatus(Store store, int ordinal) {
        Long userId = SecurityUtils.getUserId();
        if((store.getStatus() == StoreStatus.SUBMITED.ordinal() && (ordinal == StoreStatus.PASS_AUDIT.ordinal() || ordinal == StoreStatus.NO_PASS_AUDIT.ordinal()))
            || (store.getStatus() == StoreStatus.PASS_AUDIT.ordinal() && ordinal == StoreStatus.STOPED.ordinal())){
            LambdaUpdateWrapper<Store> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Store::getId,store.getId())
                    .set(Store::getStatus,ordinal);
            updateWrapper.set(Store::getUpdateTime,DateUtils.getNowDate());
            updateWrapper.set(Store::getUpdateBy,userId);
            int i = storeMapper.update(null, updateWrapper);
            if(i > 0){
                return true;
            }else{
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean deleteById(Long id) {
        LambdaUpdateWrapper<Store> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Store::getIsDeleted, ExistStatus.NO_EXIST_STATUS.ordinal());
        updateWrapper.eq(Store::getId,id);
        int i = storeMapper.update(null, updateWrapper);
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteByIds(List<Long> idLongList) {
        for (Long id:idLongList
        ) {
            boolean b = deleteById(id);
            if(!b){
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean updateOrSave(Store store) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();
        store.setUpdateTime(DateUtils.getNowDate());
        store.setUpdateBy(userName);
//        新建商店 默认一个用户只可注册一家店
        if(store.getId() == null){
            Store oldStore = selectByUserId(userId);
            if (oldStore != null){
                return false;
            }
            store.setUserId(userId);
            store.setIsDeleted(ExistStatus.EXIST_STATUS.ordinal());
            store.setCreateBy(userName);
            store.setStatus(StoreStatus.SUBMITED.ordinal());
            store.setCreateTime(DateUtils.getNowDate());
            int insert = storeMapper.insert(store);
            if(insert > 0){
                return true;
            }else{
                return false;
            }
        }else{
            // 修改店铺信息时首先查看用户的id和店铺内保存的是否一致
            LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Store::getId,store.getId());
            queryWrapper.eq(Store::getUserId,userId);
            boolean exists = storeMapper.exists(queryWrapper);
            if(!exists){
                return false;
            }
            int i = storeMapper.updateById(store);
            if(i > 0){
                return true;
            }else{
                return false;
            }
        }
    }
}
